package com.js.service.bot.response;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.js.common.annotation.ResponseClass;
import com.js.common.annotation.ResponseCommand;
import com.js.common.core.BotHandler;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.message.data.MusicKind;
import net.mamoe.mirai.message.data.MusicShare;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Scope("prototype")
@ResponseClass("音乐")
public class MusicService extends BotHandler {

    @ResponseCommand(
            value = "#点歌(.+)",
            name = "添加指令",
            reg = "#点歌"
    )
    public MessageChain song(Long userId, Long targetId, String command, MessageChain messageChain) {
        String value = getContent().get(0);
        String songResult = HttpUtil.get("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s="+value+"&type=1&offset=0&total=true&limit=9");
        if(StrUtil.isNotEmpty(songResult)){
            JSONObject res = JSONUtil.parseObj(songResult).getJSONObject("result");
            JSONArray songs = res.getJSONArray("songs");
            LinkedHashMap<String, JSONObject> map = new LinkedHashMap<>();
            for (int i = 0; i < songs.size(); i++) {
                JSONObject song = songs.getJSONObject(i);
                String singer = song.getJSONArray("artists").getJSONObject(0).getStr("name");
                if(!map.containsKey(singer)){
                    map.put(singer, song);
                }
            }
            Map<String, Object> sendSong = new HashMap<>();
            sendSong.put("sendSong", map);
            setCache("sendSong", sendSong);
            if(map.size() == 1){
                //直接发歌
                return sendSong(userId, targetId, "", messageChain);
            }else{
                //选择列表
                MessageChainBuilder result = new MessageChainBuilder();
                result.append("请输入编号选择：");
                result.append(newline());
                int i = 1;
                for (Iterator it = map.keySet().iterator(); it.hasNext();) {
                    String s = it.next().toString();
                    result.append(i + " " + map.get(s).getStr("name") + "-" + s);
                    result.append(newline());
                    i++;
                }
                return result.build();
            }
        }
        return null;
    }

    public MessageChain sendSong(Long userId, Long targetId, String command, MessageChain messageChain){
        if(!containCache("sendSong")){
            return null;
        }
        Map<String, Object> sendSong = getCache("sendSong");
        LinkedHashMap<String, JSONObject> map = (LinkedHashMap<String, JSONObject>)sendSong.get("sendSong");
        if(!NumberUtil.isNumber(messageChain.contentToString())){
            return null;
        }
        int index = Integer.parseInt(messageChain.contentToString());
        if(map.size() < index){
            return null;
        }
        JSONObject song = null;
        int i = 1;
        for (Iterator it = map.keySet().iterator(); it.hasNext();) {
            String key = it.next().toString();
            if(i == index){
                song = map.get(key);
                break;
            }
            i++;
        }
        if(song != null){
            MessageChainBuilder result = new MessageChainBuilder();
            JSONArray artists = song.getJSONArray("artists");
            String summary = artists.stream().map(artist -> JSONUtil.parseObj(artist).getStr("name"))
                    .collect(Collectors.joining("/"));
            MusicShare musicShare = new MusicShare(
                    MusicKind.NeteaseCloudMusic,
                    song.getStr("name"),
                    summary,
                    "https://y.music.163.com/m/song?id=" + song.getStr("id"),
                    artists.getJSONObject(0).getStr("img1v1Url"),
                    "http://music.163.com/song/media/outer/url?id=" + song.getStr("id"),
                    "[分享]" + song.getStr("name")
                    );
            result.append(musicShare);
            return result.build();
        }
        return null;
    }
}
